<template>
    <!-- 历史治疗申请 -->
    <div class="app-container">
        <div class="head-container-app-sole-lishi">
            <div class="yzlb">
                医嘱列表 &nbsp;<el-input v-model="searchParams.treatmentNameOrRef" placeholder="项目名称" class="width-200"
                    clearable />
            </div>
            <div>
                开始时间:
                <el-date-picker v-model="startEndTime" type="daterange" range-separator="-" start-placeholder="开始日期"
                    end-placeholder="结束日期" class="width-230" value-format="yyyy-MM-dd" />
            </div>

            <el-select v-model="searchParams.adviceStates" placeholder="全部状态" class="left-select width-150" clearable>
                <el-option v-for="item in state.list" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>

            <el-select v-model="searchParams.applyDepartmentCode" placeholder="开单科室" class="left-select width-150"
                clearable>
                <el-option v-for="item in billingAbteilung" :key="item.departmentCode" :label="item.departmentName"
                    :value="item.departmentCode" />
            </el-select>

            <el-select v-model="searchParams.applyDoctorId" placeholder="开单医生" class="left-select width-150" clearable>
                <el-option v-for="item in doctor" :key="item.aid" :label="item.realname" :value="item.aid" />
            </el-select>

            <el-button type="primary" size="mini" class="left-btn" @click="clickSearch">查询</el-button>

            <el-button type="primary" size="mini" class="left-btn" @click="batchCancellation">批量作废</el-button>
        </div>

        <el-table :data="tableData" v-loading="loading" style="width: 100%" class="left-table" fit
            :cell-style="{ 'text-align': 'center' }" :header-cell-style="{
                background: '#eef1f6',
                color: '#606266',
                textAlign: 'center',
            }" border @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="55" :selectable="isRowSelectable" />
            <el-table-column type="index" label="序号" />
            <el-table-column prop="patientName" label="姓名" />
            <el-table-column prop="gender" label="性别">
                <template #default="{ row }">
                    {{ row.gender == 1 ? '男' : '女' }}
                </template>
            </el-table-column>
            <el-table-column prop="bedNum" label="床号" />
            <el-table-column prop="admissionNum" label="住院号" />
            <el-table-column prop="applyTime" label="医嘱开立时间" width="150" />
            <el-table-column prop="adviceStates" label="状态" width="100">
                <template #default="{ row }">
                    <el-tag v-if="getState(row.adviceStates, 'label')" :type="getState(row.adviceStates, 'type')">
                        <!-- {{ state.list.find(item => item.value == row.adviceStates).label }} -->
                        {{ getState(row.adviceStates, 'label') }}
                    </el-tag>
                </template>
            </el-table-column>
            <el-table-column prop="treatmentName" label="项目名称" />
            <el-table-column prop="applyDepartmentName" label="申请科室" />
            <el-table-column prop="applyDoctor" label="申请医生" />
            <el-table-column prop="batchId" label="批次ID" v-if="false" />
            <el-table-column prop="adviceId" label="医嘱ID" v-if="false" />
            <el-table-column label="操作" width="240">
                <template #default="{ row }">
                    <!-- <el-link type="primary" v-show="row.adviceStates == 0" @click="clickEdit(row)">修改</el-link> -->
                    <el-link type="success" v-show="row.adviceStates != 0" @click="clickDetail(row)">详情</el-link>
                    <el-link type="danger"
                        v-show="row.adviceStates == 3 || row.adviceStates == 2 || row.adviceStates == 1"
                        @click="clickDel(row)">作废</el-link>
                </template>
            </el-table-column>
        </el-table>

        <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
            :current-page="searchParams.page" :page-sizes="[10, 20, 30, 50]" :page-size="searchParams.size"
            layout="total, sizes, prev, pager, next, jumper" :total="total">
        </el-pagination>


    </div>
</template>

<script>
import { historyCureApplyForList, queryRoleList, queryAbteilungList, cancellationOrder } from "@/api/residentPhysician/cureBilling.js";
import moment from 'moment'
export default {
    name: "historyApply",
    data() {
        return {
            dialog: false,
            state: {
                list: [
                    {
                        value: "0",
                        label: "未提交",
                        state: 'info'
                    },
                    {
                        value: "1",
                        label: "已提交",
                        state: 'primary'
                    },
                    {
                        value: "2",
                        label: "已签署",
                        state: 'primary'
                    },
                    {
                        value: "3",
                        label: "执行中",
                        state: 'warning'
                    },
                    {
                        value: "4",
                        label: "已完成",
                        state: 'success'
                    },
                    {
                        value: "5",
                        label: "已作废",
                        state: 'danger'
                    },
                ],
                map: {
                    0: '未提交',
                    1: '已提交',
                    2: '已签署',
                    3: '执行中',
                    4: '已完成',
                    5: '已作废'
                }
            },
            loading: false,
            batch: [],  //表格多选
            billingAbteilung: [],  //开单科室列表
            doctor: [],   //医生列表
            startEndTime: [],  //开始和结束时间
            total: 0,   //数据总条数
            searchParams: {
                treatmentNameOrRef: "",  //治疗项目名称或简称
                applyTimeBegin: "",  //医嘱提交开始时间  格式 yyyy-MM-dd
                applyTimeEnd: "",   //医嘱提交结束时间  格式 yyyy-MM-dd
                adviceStates: "",   //医嘱状态：不传=全部  0=未提交 1=已提交 2=已签署 3=执行中 4=已完成 5=已作废
                applyDepartmentCode: "",   //申请科室编码
                applyDoctorId: "",   //申请医生ID
                page: 1,
                size: 10,
                queryPage: 2
            },
            tableData: [],
        };
    },
    methods: {
        // 匹配状态
        getState(adviceStates, key) {
            let data = this.state.list.find(item => item.value == adviceStates);
            if (data) return data[key];
        },
        //获取科室列表
        getAbteilungList() {
            let params = {
                page: 1,
                size: 10
            }
            queryAbteilungList(params).then(response => {
                let { code, content } = response;
                if (code === 0 && content) {
                    this.billingAbteilung = content;
                } else {
                    this.billingAbteilung = [];
                }
            }).catch(err => {
                console.log(err);
            })
        },
        //获取医生列表
        getDoctorList() {
            queryRoleList({ roleId: 2 }).then(response => {
                let { code, content } = response;
                if (code === 0 && content) {
                    this.doctor = content;
                } else {
                    this.doctor = [];
                }
            }).catch(err => {
                console.log(err);
            })
        },
        //获取历史治疗申请列表
        getCureApplyForList() {
            this.loading = true;
            if (this.startEndTime) {
                this.searchParams.applyTimeBegin = this.startEndTime[0];
                this.searchParams.applyTimeEnd = this.startEndTime[1];
            }
            historyCureApplyForList(this.searchParams).then(response => {
                let { code, content, totalElements } = response;
                if (code === 0 && content) {
                    content.forEach(item => item.applyTime = moment(item.applyTime).format('YYYY-MM-DD HH:mm:ss'));
                    this.tableData = content;
                    this.total = totalElements;
                } else {
                    this.tableData = [];
                }
                setTimeout(() => { this.loading = false; }, 300)
            }).catch(err => {
                console.log(err);
                this.$notify({
                    title: '提示',
                    message: '网络出差了,请稍后再试',
                    type: 'danger'
                });
                setTimeout(() => { this.loading = false; }, 300)
            })
        },
        //表格多选
        handleSelectionChange(value) {
            this.batch = value;
        },
        //点击查询
        clickSearch() {
            this.searchParams.page = 1;
            this.getCureApplyForList();
        },
        //已作废不可勾选
        isRowSelectable(row) {
            if (
                row.adviceStates == 1 ||
                row.adviceStates == 2 ||
                row.adviceStates == 3
            ) {
                return true;
            } else {
                return false;
            }

            // return row.adviceStates != 1 ? false : row.adviceStates != 2?false:row.adviceStates != 3?false:true;
        },

        //批量作废
        batchCancellation() {
            if (!this.batch.length) {
                this.$notify({
                    title: '提示',
                    message: '请先选择治疗申请',
                    type: 'warning'
                });
                return;
            }
            let adviceIdList = this.batch.map(item => item.adviceId);
            this.clickDel(adviceIdList);
        },
        //确定作废
        confirmCancellation(adviceIdList) {
            let tip = adviceIdList.lenght > 1 ? '多条医嘱作废成功！' : '该条医嘱作废成功！';
            cancellationOrder({ adviceIdList }).then(response => {
                let { code, content, msg } = response;
                if (code === 0 && content) {
                    this.$notify({
                        title: '提示',
                        message: tip,
                        type: 'success'
                    });
                    this.getCureApplyForList();
                } else {
                    this.$notify({
                        title: '提示',
                        message: msg,
                        type: 'warning'
                    });
                }
            }).catch(err => {
                console.log(err);
                this.$notify({
                    title: '提示',
                    message: '网络出差了,请稍后再试!',
                    type: 'danger'
                });
            })
        },

        // 处理每页显示条数变化的逻辑
        handleSizeChange(value) {
            this.searchParams.size = value;
            this.getCureApplyForList();
        },
        handleCurrentChange(value) {
            // 处理当前页码变化的逻辑
            this.searchParams.page = value;
            this.getCureApplyForList();
        },
        //点击修改
        clickEdit(row) {
            this.$store.commit("setBatchId", row.batchId);
            this.$store.commit("setIsReviseBtn", true);
            this.$router.push({ name: 'cureBilling', params: { batchId: row.batchId } });
        },
        // 点击详情
        clickDetail(row) {
            this.$store.commit("setBatchId", row.batchId);
            this.$store.commit("setIsReviseBtn", false);
            this.$router.push({ name: 'OrderDetail', params: { batchId: row.batchId } });
        },
        //点击作废
        clickDel(row) {
            let tip = Array.isArray(row) ? '是否确定作废多条医嘱？' : '是否确定作废该条医嘱？';
            this.$confirm(tip, "提示", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning",
            }).then(() => {
                let arr = Array.isArray(row) ? row : [row.adviceId];
                this.confirmCancellation(arr);
            }).catch(() => {
                javascript: ;
            });
        },
    },
    watch: {
        'searchParams.adviceStates': {
            handler(newValue, oldValue) {
                if (newValue === '') {
                    this.searchParams.page = 1;
                    this.getCureApplyForList();
                }
            }
        },
        startEndTime: {
            handler() {
                if (!this.startEndTime) {
                    this.searchParams.applyTimeBegin = '';
                    this.searchParams.applyTimeEnd = '';
                }
            },
        },

    },
    mounted() {
        this.getCureApplyForList();
        this.getDoctorList();
        this.getAbteilungList();
    }

};
</script>

<style lang='scss' scoped>
.app-container {
    background-color: #fff;

    .width-100 {
        width: 100px;
    }

    .width-150 {
        width: 150px;
    }

    .width-180 {
        width: 180px;
    }

    .width-200 {
        width: 200px;
    }

    .width-230 {
        width: 230px;
    }

    .head-container-app-sole-lishi {
        display: flex;
        flex-wrap: wrap;
        align-items: center;

        .yzlb {
            font-weight: 600;
            margin-right: 10px;
        }

        .left-select,
        .left-btn {
            margin-left: 10px !important;
        }
    }

    .el-table {
        margin-bottom: 5px;

        .el-link {
            margin: 0 10px;
        }
    }

    .el-pagination {
        display: flex;
        align-items: center;
        justify-content: center;
    }

    #btn {
        margin-bottom: 10px;
    }
}
</style>